package cn.bincker.web.blog.base.service.impl;

import cn.bincker.web.blog.base.entity.FriendLink;
import cn.bincker.web.blog.base.exception.BadRequestException;
import cn.bincker.web.blog.base.exception.NotFoundException;
import cn.bincker.web.blog.base.repository.IFriendLinkRepository;
import cn.bincker.web.blog.base.service.IFriendLinkService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class FriendLinkServiceImpl implements IFriendLinkService {
    private final IFriendLinkRepository friendLinkRepository;

    public FriendLinkServiceImpl(IFriendLinkRepository friendLinkRepository) {
        this.friendLinkRepository = friendLinkRepository;
    }

    @Override
    public FriendLink add(FriendLink friendLink) {
        var target = new FriendLink();
        target.setStatus(FriendLink.Status.PENDING);
        target.setTitle(friendLink.getTitle().trim());
        target.setFavicon(friendLink.getFavicon().trim());
        target.setUrl(friendLink.getUrl().trim().replaceAll("/+$", ""));
        var likeFriendLink = friendLinkRepository.findByUrl(target.getUrl());
        if(likeFriendLink.isPresent()){
            String msg = "";
            switch (likeFriendLink.get().getStatus()){
                case NORMAL -> msg = "该友链已添加";
                case PENDING -> msg = "博主正在审核该友链，请等一下下";
                case FORBIDDEN -> msg = "该友链已经被博主禁用了，如贵站符合要求请联系博主或留言";
            }
            throw new BadRequestException("申请已存在的友链: url=" + friendLink.getUrl(), msg);
        }
        return friendLinkRepository.save(target);
    }

    @Override
    public void delete(Long id) {
        friendLinkRepository.deleteById(id);
    }

    @Override
    public FriendLink update(FriendLink friendLink) {
        var target = friendLinkRepository.findById(friendLink.getId()).orElseThrow(NotFoundException::new);
        target.setUrl(friendLink.getUrl());
        target.setTitle(friendLink.getTitle());
        target.setStatus(friendLink.getStatus());
        target.setFavicon(friendLink.getFavicon());
        return friendLinkRepository.save(target);
    }

    @Override
    public List<FriendLink> list() {
        return friendLinkRepository.findAllByStatus(FriendLink.Status.NORMAL);
    }

    @Override
    public Page<FriendLink> page(String keywords, FriendLink.Status status, Pageable pageable) {
        if(keywords == null) keywords = "";
        if(status == null) {
            return friendLinkRepository.findAllByKeywordsLike("%" + keywords + "%", pageable);
        }else{
            return friendLinkRepository.findAllByKeywordsLike("%" + keywords + "%", status, pageable);
        }
    }
}
